package edu.ecust.design.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import edu.ecust.design.dao.SuppliersMapper;
import edu.ecust.design.domain.Suppliers;
import edu.ecust.design.domain.SuppliersExample;
import edu.ecust.design.domain.SuppliersExample.Criteria;
import edu.ecust.design.domain.dto.SuppliersParams;
import edu.ecust.design.service.ISuppliersServive;
import edu.ecust.design.web.model.Limit;
import edu.ecust.design.web.model.Page;

@Service
public class SuppliersServiveImpl implements ISuppliersServive {
	@Autowired
	private SuppliersMapper suppliersMapper;

	@Override
	public Page<Suppliers> searchFullText(String search, Limit limit) {
		SuppliersParams params = new SuppliersParams();
		params.setSearch(search);
		params.setLimit(limit);
		List<Suppliers> list = suppliersMapper.selectFullText(params);
		int count = suppliersMapper.countFullText(params);
		return new Page<Suppliers>(list, limit, count);
	}

	@Override
	public long save(Suppliers supp) {
		Assert.notNull(supp, "Suppliers is null");
		try {
			suppliersMapper.insertSelective(supp);
		} catch (DuplicateKeyException e) {
			String supName = supp.getSupName();
			String contact = supp.getContact();
			Suppliers existsSupp = findSuppliersByUserAndCrop(supName, contact);
			Long id = existsSupp.getId();
			supp.setId(id);
			update(supp);
		}
		return supp.getId();
	}

	@Override
	public int update(Suppliers supp) {
		Assert.notNull(supp, "Suppliers is null");
		Long id = supp.getId();
		Assert.notNull(id, "Suppliers id is null");
		return suppliersMapper.updateByPrimaryKeySelective(supp);
	}

	@Override
	public int delete(Long id) {
		return suppliersMapper.deleteByPrimaryKey(id);
	}

	@Override
	public Suppliers findSuppliersByUserAndCrop(String supName, String contact) {
		Assert.notNull(supName, "supName must not null");
		Assert.notNull(contact, "contact must not null");
		SuppliersExample exa = new SuppliersExample();
		Criteria c = exa.createCriteria();
		c.andSupNameEqualTo(supName);
		c.andContactEqualTo(contact);
		List<Suppliers> supps = suppliersMapper.selectByExample(exa);
		if (supps.size() > 0) {
			return supps.get(0);
		}
		return null;
	}
}
